package com.atguigu.gmall.gateway.config;

import com.atguigu.gmall.gateway.exception.GlobalJsonErrorHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.stream.Collectors;

@Configuration
public class ExceptionHandlerConfig {
    //将自定义异常处理器对象注入到容器中
    @Bean
    @Order(-1)
    public GlobalJsonErrorHandler jsonExceptionHandler(ErrorAttributes errorAttributes,
                                                       org.springframework.boot.autoconfigure.web.ResourceProperties resourceProperties,
                                                       ServerProperties serverProperties,
                                                       ObjectProvider<ViewResolver> viewResolvers,
                                                       ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext){

        GlobalJsonErrorHandler handler = new GlobalJsonErrorHandler(errorAttributes, resourceProperties,
                serverProperties.getError(), applicationContext);
        handler.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()));
        handler.setMessageWriters(serverCodecConfigurer.getWriters());
        handler.setMessageReaders(serverCodecConfigurer.getReaders());
        return handler;
    }
}